﻿using FileSearchTool.ui;
using Microsoft.VisualBasic.FileIO;
using SimpleConnection_UDP_WIN.utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using WindowsImageCompressionApp.utils;

using SearchOption = System.IO.SearchOption;

namespace FileSearchTool
{
    public partial class Form1 : Form
    {

        string lastDir;

        public Form1()
        {
            InitializeComponent();
        }

        private const int WM_HOTKEY = 0x0312;
        private const int HOTKEY_ID = 1;

        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            if (m.Msg == WM_HOTKEY)
            {
                int id = m.WParam.ToInt32();
                if (id == HOTKEY_ID)
                {
                    // 处理全局热键事件
                    HandleHotkey();
                }
            }
        }

        private void HandleHotkey()
        {
            this.WindowState =(this.WindowState == FormWindowState.Minimized)? FormWindowState.Normal: FormWindowState.Minimized;

        }


        private void Form1_Load(object sender, EventArgs e)
        {

            int width = Screen.PrimaryScreen.WorkingArea.Width / 50 * 12;

            this.MaximumSize = new Size(width, Screen.PrimaryScreen.WorkingArea.Height);
            this.MinimumSize = new Size(width, Screen.PrimaryScreen.WorkingArea.Height / 10 * 5);


            //初始化 位置
            Size = new Size(width, Screen.PrimaryScreen.WorkingArea.Height);
            Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - width, 0);

            setLastDir(RegistryUtils.getString("lastDir", ""));

            menuItem2.Checked = RegistryUtils.getBool("topMost", false);
            menuItem4.Checked = RegistryUtils.getBool("MinimizeAfterOpeningFile", true);
            menuItem5.Checked = RegistryUtils.getBool("DeepSearch", true);

            menuItem8.Checked = RegistryUtils.getBool("ClearEditBox", true);
            menuItem9.Checked = RegistryUtils.getBool("DisplayFloatingWindow", true);

            this.TopMost = menuItem2.Checked;
            textBox1.Focus();


            // 注册全局热键F7，使用Ctrl修饰键
            RegisterHotKey(this.Handle, HOTKEY_ID, 0x0000, (int)Keys.F7);

        }


        private void setLastDir(string dir)
        {
            lastDir = dir;

            if (!string.IsNullOrWhiteSpace(lastDir))
            this.Text = $"在 {lastDir} 中搜索：";
        }

        private void menuItem3_Click(object sender, EventArgs e)
        {
            // 创建 FolderBrowserDialog 实例
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog
            {
                // 设置默认路径
                RootFolder = Environment.SpecialFolder.Desktop,
                Description = $"当前扫描根目录：{RegistryUtils.getString("lastDir", "未设置")}"
            };

            // 显示对话框
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                string folderPath = folderBrowserDialog.SelectedPath;
                // 在这里处理你选择的文件夹路径
                if (Directory.Exists(folderPath))
                {

                    setLastDir(folderPath);
                    RegistryUtils.setString("lastDir", lastDir);

                    MessageBox.Show($"设置成功:{lastDir}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("设置失败，目录不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }

            }

        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            menuItem2.Checked = !menuItem2.Checked;
            this.TopMost = menuItem2.Checked;
            RegistryUtils.setBool("topMost", menuItem2.Checked);
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //编辑框变动，触发搜索，如果吃性能可以改为 启动软件开始索引，
            if (string.IsNullOrWhiteSpace(textBox1.Text)) { return; }

            bool isAll = currentlySelectedFilter.Equals("全部类型");
            searchStart(isAll ? $"*{textBox1.Text}*" : $"*{textBox1.Text}*{currentlySelectedFilter}", !isAll);

        }

        List<FileInfo> fileInfos = new List<FileInfo>();
        HashSet<string> extensions = new HashSet<string>();

        private void searchStart(string keyword, bool isFilter)
        {
            listBox1.Items.Clear();
            fileInfos.Clear();
            extensions.Clear();
            toolStripStatusLabel3.Text = "未找到文件";

            extensions.Add("全部类型");

            if (!Directory.Exists(RegistryUtils.getString("lastDir", "")))
            {
                MessageBox.Show("搜索失败，扫描目录不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            foreach (string file in Directory.GetFiles(lastDir, keyword, menuItem5.Checked ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
            {

                // if (file.Contains(keyword))
                // {
                string extension = Path.GetExtension(file);
                fileInfos.Add(new FileInfo(file));
                extensions.Add(extension);
                //  }
            }

            foreach (FileInfo fileInfo in fileInfos)
            {
                if (fileInfo.Exists)
                {
                    listBox1.Items.Add(fileInfo.Name.Replace(" ", "")
                        .Replace("_", "")
                        .Replace("~", "")
                        .Replace("$", "")
                        .Replace("#", "")
                        );

                    toolStripStatusLabel3.Text = listBox1.Items.Count.ToString();
                }
            }


            if (!isFilter)
            {

                toolStripDropDownButton1.DropDownItems.Clear();
                foreach (string extension in extensions)
                {
                    // 创建一个新的ToolStripMenuItem实例
                    ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem
                    {
                        Text = extension
                    };

                    //  toolStripMenuItem.DropDownItemClicked += new ToolStripItemClickedEventHandler(toolStripDropDownItem_DropDownItemClicked);
                    toolStripMenuItem.Click += new EventHandler(toolButtonsClick);
                    // 将ToolStripMenuItem添加到ToolStripDropDownButton的DropDownItems集合中
                    toolStripDropDownButton1.DropDownItems.Add(toolStripMenuItem);
                }

            }

            toolStripDropDownButton1.Text = $"当前过滤器：{currentlySelectedFilter}";

        }
        // Handle the buttons' click event by setting the foreground color of the
        // form to the foreground color of the button that is clicked.
        private void toolButtonsClick(object sender, EventArgs e)
        {
            ToolStripItem senderButton = (ToolStripItem)sender;
            Console.WriteLine(senderButton.Text);

            //编辑框变动，触发搜索，如果吃性能可以改为 启动软件开始索引，
            if (string.IsNullOrWhiteSpace(textBox1.Text)) { return; }


            currentlySelectedFilter = senderButton.Text;

            bool isAll = currentlySelectedFilter.Equals("全部类型");
            searchStart(isAll ? $"*{textBox1.Text}*" : $"*{textBox1.Text}*{currentlySelectedFilter}", !isAll);

        }

        //初始化为
        string currentlySelectedFilter = "全部类型";



        private void menuItem4_Click(object sender, EventArgs e)
        {
            menuItem4.Checked = !menuItem4.Checked;
            RegistryUtils.setBool("MinimizeAfterOpeningFile", menuItem4.Checked);

        }

        private void menuItem5_Click(object sender, EventArgs e)
        {
            menuItem5.Checked = !menuItem5.Checked;
            RegistryUtils.setBool("DeepSearch", menuItem5.Checked);

            //编辑框变动，触发搜索，如果吃性能可以改为 启动软件开始索引，
            if (string.IsNullOrWhiteSpace(textBox1.Text)) { return; }
            searchStart($"*{textBox1.Text}*", false);

        }

        private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (listBox1.SelectedIndex == -1)
            { return; }

            if (e.Button == MouseButtons.Left)
            {
                // 点击的是鼠标左键
                // 在这里添加你的代码
                if (fileInfos[listBox1.SelectedIndex].Exists)
                {
                    DBUtil.openFile(fileInfos[listBox1.SelectedIndex].FullName);
                    if (menuItem4.Checked)
                    {
                        this.WindowState = FormWindowState.Minimized;
                    }
                }

            }
 

        }

        private void menuItem7_Click(object sender, EventArgs e)
        {
            new AboutBox1().ShowDialog();
        }


        private void addInfoListData(params object[] info)
        {
            infoForm.listBox1.Items.Clear();

            foreach (object item in info)
            {
                infoForm.listBox1.Items.Add(item);
            }
        }


        InfoForm infoForm = new InfoForm();

        private void listBox1_MouseClick(object sender, MouseEventArgs e)
        {


            if (listBox1.SelectedIndex == -1)
            { return; }

            if (e.Button == MouseButtons.Left)
            {

                if (menuItem9.Checked)
                {

                    if (infoForm == null || infoForm.IsDisposed)
                    {
                        infoForm.Show();//未打开，直接打开。
                    }
                    else
                    {

                        infoForm.Visible = true;

                        addInfoListData(
                            $"名称：{fileInfos[listBox1.SelectedIndex].Name}",
                            $"扩展名：{fileInfos[listBox1.SelectedIndex].Extension}",
                            $"完整路径：{fileInfos[listBox1.SelectedIndex].FullName}",
                            $"父目录：{fileInfos[listBox1.SelectedIndex].Directory.Name}",
                            $"体积：{DBUtil.FormatFileSize(fileInfos[listBox1.SelectedIndex].Length)}",
                            $"最后更新日期：{fileInfos[listBox1.SelectedIndex].LastWriteTime.GetDateTimeFormats()[63]}",
                            $"HashCode：{fileInfos[listBox1.SelectedIndex].GetHashCode()}"
                            );

                    }

                }



            }
      

        }



        private void listBox1_MouseLeave(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex == -1)
            { return; }


            if (infoForm == null)
                return;
            infoForm.Visible = false;

        }


        private void Form1_Resize(object sender, EventArgs e)
        {
            if (menuItem8.Checked)
            {
                textBox1.Text = string.Empty;
            }

            textBox1.Focus();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 注销全局热键
            UnregisterHotKey(this.Handle, HOTKEY_ID);
        }

        private void menuItem8_Click(object sender, EventArgs e)
        {
            menuItem8.Checked = !menuItem8.Checked;
            RegistryUtils.setBool("ClearEditBox", menuItem8.Checked);

        }


        private void listBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {

                if (listBox1.SelectedIndex == -1)
                { return; }

                infoForm.Visible = false;

                var filePath = fileInfos[listBox1.SelectedIndex].FullName;

                // 创建一个上下文菜单
                ContextMenu menu = new ContextMenu();
                menu.MenuItems.Add("打开");
                menu.MenuItems.Add("打开所在位置");
                menu.MenuItems.Add("复制");
                menu.MenuItems.Add("删除");
    
                menu.Show(listBox1, new Point(e.X, e.Y));
                menu.MenuItems[0].Click += delegate
                {
                    // 点击的是鼠标左键
                    // 在这里添加你的代码
                    if (fileInfos[listBox1.SelectedIndex].Exists)
                    {
                        DBUtil.openFile(fileInfos[listBox1.SelectedIndex].FullName);
                        if (menuItem4.Checked)
                        {
                            this.WindowState = FormWindowState.Minimized;
                        }
                    }
                };
                menu.MenuItems[1].Click += delegate
                {
                    // 使用 "/select" 参数打开文件所在目录，并选中该文件
                    Process.Start("explorer.exe", $"/select,\"{filePath}\"");

                };
                menu.MenuItems[2].Click += delegate
                {

                    Clipboard.SetFileDropList(new System.Collections.Specialized.StringCollection { filePath });


                };
                menu.MenuItems[3].Click += delegate
                {

                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    DialogResult dr = MessageBox.Show("确定要放到回收站吗?", "警告", messButton,MessageBoxIcon.Warning);
                    if (dr == DialogResult.OK)
                    {
                        if (File.Exists(filePath))
                        {
                            FileSystem.DeleteFile(filePath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                        }
                    }
                };
            
            }
        }

        private void menuItem9_Click(object sender, EventArgs e)
        {
            menuItem9.Checked = !menuItem9.Checked;
           
            RegistryUtils.setBool("DisplayFloatingWindow", menuItem9.Checked);

        }
    }
}
